package im.xz.cn.xiachat;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.plugin.Plugin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Timer;
import java.util.TimerTask;

public class xiazhi implements Listener {
    Plugin plugin = im.xz.cn.xiachat.XiaChat.getPlugin(im.xz.cn.xiachat.XiaChat.class);

    String BASE_URL = plugin.getConfig().getString("apiUrl");
    String API_KEY = plugin.getConfig().getString("apiKey");
    String PromptSystem = plugin.getConfig().getString("systemPrompt");
    String PromptUser = plugin.getConfig().getString("userPrompt");
    String model = plugin.getConfig().getString("model");
    final ConcurrentHashMap<String, Boolean> playerRequestStatus = new ConcurrentHashMap<>();

    private boolean startRequestFor(Player player) {
        String playerName = player.getName();
        if (playerRequestStatus.containsKey(playerName) && playerRequestStatus.get(playerName)) {
            return false;
        } else {
            playerRequestStatus.put(playerName, true);
            // 设置定时器自动取消请求防止死锁
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    playerRequestStatus.remove(playerName);
                }
            }, 60000); // 超时时间为60秒
            return true;
        }
    }

    @EventHandler
    public void chat(AsyncPlayerChatEvent event) throws IOException {
        Player player = event.getPlayer();
        String message = event.getMessage();

        if (message.startsWith("xc ") && !startRequestFor(player)) {
            player.sendMessage("xiaChat | 前条消息处理中");
            event.setCancelled(true);
            return;
        } else if (message.startsWith("xc ")) {
            event.setCancelled(true);
            player.sendMessage("<" + player.getName() + "> " + event.getMessage());
            handleAIRequest(player, message.replace("xc ", ""));
        }
    }

    private void handleAIRequest(Player player, String formatMessage) {
        CompletableFuture.runAsync(() -> {
            try {
                URL url = new URL(BASE_URL);
                String name = player.getName();
                String formattedMessage = PromptUser + "，我的名字是" + name + ",我想请问：" + formatMessage;
                String jsonInputString = "{"
                        + "\"model\": \"" + model +"\", "
                        + "\"messages\": ["
                        + "    {\"role\": \"system\", \"content\": \"" + PromptSystem +"\"}, "
                        + "    {\"role\": \"user\", \"content\": \"" + formattedMessage + "\"}"
                        + "], "
                        + "\"stream\": false"
                        + "}";

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Authorization", "Bearer " + API_KEY);

                try (OutputStream os = conn.getOutputStream()) {
                    byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(
                            conn.getInputStream(), StandardCharsets.UTF_8));
                    String inputLine;
                    StringBuilder response = new StringBuilder();

                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode rootNode = objectMapper.readTree(response.toString());
                    JsonNode choicesNode = rootNode.path("choices").get(0);
                    JsonNode messageNode = choicesNode.path("message");

                    if (messageNode.has("content") && !messageNode.get("content").isNull()) {
                        String content = messageNode.get("content").asText();
                        player.sendMessage("<xiaChat> §o" + content);
                        System.out.println(name + "询问xiaChat: " + formatMessage);
                        System.out.println("回复" + name + ": " + content);
                    } else {
                        System.out.println("Content field is missing or null.");
                    }
                } else {
                    player.sendMessage("xiaChat | 请求失败，返回码：" + conn.getResponseCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                playerRequestStatus.remove(player.getName());
            }
        });
    }
}